// pages/release-mt/release-mt.js
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var isPosting = false;
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: 'artartimages',
  operator: 'upyunadmin2014',
  getSignatureUrl: 'https://api.artart.cn/api.php?ac=signupyun&publickey=' + util.publiccode
});
var oldData = '';
var isEdit = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    minHeight: 0,
    uploadImg: [],
    token: "",
    uid: 0,
    imgWH: 0,
    titleValue: '',
    linkValue: '',
    date:'',
    startDate:'',
    endDate:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    oldData = '';
    isEdit = false;
    if (options.data) {//有数据传过来，说明是编
      wx.showLoading({
        title: '加载中',
      })
      oldData = JSON.parse(options.data);
      isEdit = true;
      console.log("要编辑的数据：", oldData);
    }
    var curDate = new Date();
    var curYear = curDate.getFullYear();
    var curDate_f = util.formatTime(curDate, '-', '');
    var startDate_f = util.formatTime(new Date(curYear-50, 0, 1), '-', '');
    var endDate_f = util.formatTime(new Date(curYear + 49, 11, 31), '-', '');
    console.log("curDate_f = " + curDate_f + "; startDate_f = " + startDate_f + "; endDate_f = " + endDate_f);
    this.setData({
      date: curDate_f,
      startDate: startDate_f,
      endDate: endDate_f
    });
    this.load();
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          token: res.token
        });
      }
    });
  },
  load: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          minHeight: res.windowHeight - 40,
          imgWH: (res.windowWidth - 18) / 4 - 12
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if(isEdit){
      var photoArray = [];
      if (oldData.photos) {
        photoArray = oldData.photos.split(',');
      }
      var source = oldData.source ? (oldData.source.username ? oldData.source.username : oldData.source) : ''; 
      this.setData({
        titleValue: oldData.topictitle,
        sourceValue: source,
        date: oldData.age,
        linkValue: oldData.message,
        uploadImg: photoArray,
      });
      wx.hideLoading();
    }
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  releaseSubmit: function (e) {
    if (isPosting) {
      return false;
    }
    isPosting = true;

    var title = e.detail.value.title;//标题
    if(!title || title.trim().length <= 0){
      app.dialog('请输入标题', 'loading');
      isPosting = false;
      return false;
    }
    var source = e.detail.value.source;
    if (!source || source.trim().length <= 0) {
      app.dialog('请输入来源', 'loading');
      isPosting = false;
      return false;
    }
    var date = this.data.date;
    if (!date || date.trim().length <= 0) {
      app.dialog('请选择时间', 'loading');
      isPosting = false;
      return false;
    }
    var link = e.detail.value.newslink;//链接
    if (!link || link.trim().length <= 0) {
      app.dialog('请输入链接', 'loading');
      isPosting = false;
      return false;
    }

    // wx.showLoading({ title: '发布中，请稍等' });
    wx.showLoading({ title: '发布中...' });
    
    //图片
    var photos = this.data.uploadImg;//选择的图片 	图片的本地文件路径列表
    var photos_param = "";
    if(photos && photos.length > 0) {
      if (photos.length == 0) {
        app.dialog('请上传图片', 'loading');
        isPosting = false;
        return false;
      }
      //data 里面是参数  我不知道是不是用这个接口  你看着改吧  再把内容和图片放里就好了
      var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }
      photos_param = photos.map(function (item) { return item.replace('wxfile://tmp_', util.imgHost + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(',');
    }

    var action = "posttopic";
    if (isEdit) {
      action = "edittopic";
    }
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + action + token);//私钥

    var data = {
      ac: action,
      topictype: 17,
      privatekey: privatekey,
      uid: uid,
      postuid: uid,
      topictitle: title,
      source: source,
      age: date,
      message: link,
      xcx: 1,
      photos: photos_param
    }
    if (isEdit) {
      data.topicid = oldData.id;
    }
    console.log("媒体：", data);
    
    util.api({
      data: data,
      method: "POST",
      success: function (responseData) {
        console.log(responseData);
        if (responseData.data.id) {//你看是不是这个字段判断发布失败还是成功的
          // wx.redirectTo({ url: "/pages/index/index?go=dongtai" });
          wx.reLaunch({ url: "/pages/index/index?go=dongtai" });
        } else {
          app.dialog('发布失败', 'loading');
        }
        isPosting = false;
      },
      fail:function(e){
        isPosting = false;
      }
    });
  },
  uploadImgs: function () {
    var that = this;
    var photos = this.data.uploadImg;
    if (photos.length >= 9) {
      app.dialog('最多上传9张图片', 'loading');
      return false;
    }

    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
            },
            fail: function ({ errMsg }) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  //删除图片
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})